<!--
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-05-20 09:14:10
 * @LastEditTime: 2022-05-20 21:13:40
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description:
-->
<template>
  <div class="markdown-container">
    <!-- 渲染区 -->
    <div id="markdown-box"></div>
    <div class="bottom">
      <el-button
        type="primary"
        @click="onSubmitClick"
      >{{
        $t('article.commit')
      }}</el-button>
    </div>
  </div>
</template>

<script setup>
import { onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { watchSwitchLang } from '@/utils/i18n'
import MkEditor from '@toast-ui/editor'
import '@toast-ui/editor/dist/toastui-editor.css'
import '@toast-ui/editor/dist/i18n/zh-cn'
// eslint-disable-next-line no-undef
const props = defineProps({
  details: {
    type: Object
  }
})
const store = useStore()
// eslint-disable-next-line no-undef
const emits = defineEmits('submit')

let instanceMkEditor
let el
onMounted(() => {
  el = document.getElementById('markdown-box')
  createMkEditor()
})

const createMkEditor = () => {
  instanceMkEditor = new MkEditor({
    el,
    height: '500px',
    previewStyle: 'vertical',
    language: store.getters.language === 'zh' ? 'zh-CN' : 'en'
  })
  instanceMkEditor.getMarkdown()
}
// 提交文章
const onSubmitClick = () => {
  emits('submit', instanceMkEditor.getHTML(), () => {
    instanceMkEditor.reset()
  })
}
watch(() => props.details, (v) => {
  v.content && instanceMkEditor.setHTML(v.content)
})
watchSwitchLang(() => {
  if (!el) return
  const html = instanceMkEditor.getHTML()
  instanceMkEditor.destroy()
  createMkEditor()
  instanceMkEditor.setHTML(html)
})
</script>

<style lang="scss" scoped>
.markdown-container {
  .bottom {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
